import React, {  useCallback, CSSProperties, useEffect,useRef } from "react";
import { View } from "@tarojs/components";
import cls from "classnames";
import "./index.scss";
import { useSystemInfo } from "@src/hooks";
import { Animated } from "react-native";



type Props = {
    list: { text: string }[],
    onChange: Function,
    style: CSSProperties,
    current: number,
    underline?:boolean
}
const itemWidth = 80;
const slideBarWidth = 40;
const CustomTabBar = (props: Props) => {
    const list = props.list || [];
    const current = props.current;
    const underline = props.underline;
    const switchTab = useCallback((index: number) => {
        const onChange = props.onChange || (() => { });
        onChange(index);
    }, [props.onChange]);

    const { screenWidth } = useSystemInfo();


    const offsetX = (screenWidth - itemWidth * list.length) / 2 + (itemWidth - slideBarWidth) / 2;
    const translateX = useRef(new Animated.Value(offsetX + current * itemWidth)).current;


    useEffect(() => {
        if(!underline){
            return;
        }
        Animated.timing(    
            translateX,
            {
                toValue: offsetX + current * itemWidth,
                duration: 100,
                useNativeDriver: true
            }
        ).start();


    }, [current,translateX, offsetX,underline]);
    
    return (
        <View className="customTabBar" style={props.style}>
            <View className="customTabBar__items">

                {
                    list.map((item, index) => {
                        return <View className="customTabBar__item" style={{ width: itemWidth }} onClick={switchTab.bind(this, index)} key={index}>
                            <View className={cls("customTabBar__item__text", current == index ? "customTabBar__item__text--actived" : "")} >
                                {item.text}
                            </View>
                        </View>;
                    })
                }
            </View>
            {
                underline ? <Animated.View style={{
                    transform: [{ translateX: translateX }],
                    width: slideBarWidth,
                    height: 4,
                    borderRadius: 3,
                    backgroundColor: "#000",
                    position: "absolute",
                    bottom: 0
                }}
                /> : null
            }
           
        </View>

    );
};

export default React.memo(CustomTabBar);